<template>
  <div>
    <el-form
      :model="todoValidateForm"
      ref="todoValidateForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item
        label="标题"
        prop="title"
        :rules="[{ required: true, message: '标题不能为空' }]"
      >
        <el-input
          type="title"
          v-model="todoValidateForm.title"
          autocomplete="off"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input type="textarea" v-model="todoValidateForm.content"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('todoValidateForm')"
          >提交</el-button
        >

        <el-button @click="resetForm('todoValidateForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      todoValidateForm: {
        title: "",
        content: "",
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //ajos请求服务器
          let res = await this.$http.post(
            "/create-todo", // 第一个参数：url
            this.todoValidateForm //第二个参数：请求参数
          );

          let code = res.data.code; //服务端响应的操作结果代码，0=失败，1=成功
          const msgType = ["error", "success"];
          // 提示新增结果
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: msgType[code], //根据结果代码切换不同类型的提示
          });
          //如果成功跳转到备忘列表
          if (code === 1) {
            this.$router.push("/");
          }
          
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>